﻿// Overrides the event handlers from the configuration and propagates the onValueChanged notifications to the owners
define([
    'Wjs/Wjs'
],
function () {
    'use strict';

    var type = 'ValueChangedHandler', // Use the type registration to avoid recreating the type
    typeManager = Wjs.typeManager,
    ValueChangedHandler = typeManager.getType(type);

    if (ValueChangedHandler) { // It has been already loaded
        return ValueChangedHandler;
    }

    // Renders the html from a component
    ValueChangedHandler = Wjs.typeBuilder.define({

        type: type, // Set the type

        // Call it after calling Widget construct
        initialize: function (conf) {
            conf = conf || {};

            this.onValueChanged = Wjs.chain(conf.onValueChanged, this.onValueChanged); // Override this onValueChanged with the one of the configuration
        },

        onValueChanged: function () {
            var owner = this.owner,
            args = Array.prototype.slice.call(arguments);

            args.unshift(this); // Prepend source to arguments

            if (owner && owner.onValueChanged) { // Propagate to owner
                owner.onValueChanged.apply(owner, args);
            }
        }
    });

    typeManager.registerType(ValueChangedHandler);

    return ValueChangedHandler;
});